'''
    用户账号相关的功能：注册 短信 登录 注销。。

'''
import datetime
import uuid
from io import BytesIO

from django.db.models import Q
from django.shortcuts import render, redirect
from django.http import JsonResponse, HttpResponse
from django.urls import reverse

from utils.verify_code.verify_code import create_validate_code
from web import models
from web.forms.account import RegisterModelForm, SendSmsForm, LoginSmsForm, LoginForm
from web.forms.project import ProjectModelForm


def register(request):

    if request.method == 'GET':
        form = RegisterModelForm()



        return render(request, 'Register.html', locals())
    elif request.method == 'POST':
        form = RegisterModelForm(data=request.POST)#别忘了 参数 一开始form是空的 但是前端填写后发挥校验 数据都在request中
        # print(form.errors)
        if form.is_valid():
            #way 1
            instance = form.save()
            #way 2
            # username = form.cleaned_data['user_name']
            # password = form.cleaned_data['passwd']
            # email = form.cleaned_data['email']
            # mobile_phone = form.cleaned_data['mobile_phone']
            # models.UserInfo.objects.create(xxx)

            #注册成功的同时 在交易记录添加 免费会员的交易记录
            # 其中PricePolicy Transaction是1对多的关系 其中Transaction中包含外键price_policy指向PricePolicy
            # 其中UserInfo Transaction是1对多的关系 其中Transaction中包含外键user指向PricePolicy
            policy_object = models.PricePolicy.objects.filter(category=1, title="个人免费版").first()
            models.Transaction.objects.create(
                status=2,#表示已支付
                order=str(uuid.uuid4()),#uuid4()：这是基于随机数的uuid，既然是随机就有可能真的遇到相同的，但这就像中奖似的，几率超小，
                user=instance,#此处的instance 相当于是注册的用户实例
                price_policy=policy_object,
                count=0,
                price=0,
                start_datetime=datetime.datetime.now()#应为是免费帐号 所以end_datetime无需设置
            )


            return JsonResponse({'status': True, 'data': '/login/sms/'})

        else:
            return JsonResponse({'status': False, 'error': form.errors})
        # print('hello register')


def send_sms(request):
    # print(request.GET)

    # mobile_phone = request.GET.get('mobile_phone')
    # tpl = request.GET.get('tpl')

    form = SendSmsForm(request, data=request.GET)  # 初始化新建一个对象会调用它的init方法
    if form.is_valid():
        # return HttpResponse('success')
        # send message & store in redis
        return JsonResponse({'status': True})
    else:
        # return HttpResponse('tel wrong')

        return JsonResponse({'status': False, 'error': form.errors})

    # return HttpResponse('success')


# def login(request):
#     if request.method == 'GET':
#         # return HttpResponse('login success!')
#         return render(request,'')


def login_sms(request):
    form = LoginSmsForm()
    if request.method == 'GET':
        return render(request, 'login_sms.html',{'form':form})
    else:
        form = LoginSmsForm(data=request.POST)#别忘了 参数 一开始form是空的 但是前端填写后发挥校验 数据都在request中！！！
        if form.is_valid():
            mobile_phone = request.POST.get('mobile_phone',0)
            user_obj = models.UserInfo.objects.filter(mobile_phone=mobile_phone).first()
            request.session['user_id'] = user_obj.id
            request.session.set_expiry(60 * 60 * 24 * 14)
            return JsonResponse({'status': True,'data':'/index/'})
        # print({'status': False, 'error': form.errors})
        return JsonResponse({'status': False, 'error': form.errors})


def login(request):

    form = LoginForm(request)
    if request.method == "GET":
        return render(request, 'login.html', {'form': form})
    # return HttpResponse('use name and passwd to singin')
    form = LoginForm(request, request.POST)
    if form.is_valid():

        username = form.cleaned_data['username']
        password = form.cleaned_data['password']

        # user_object = models.UserInfo.objects.filter(username=username, password=password).first()
        #  (手机=username and pwd=pwd) or (邮箱=username and pwd=pwd)

        user_object = models.UserInfo.objects.filter(Q(email=username) | Q(mobile_phone=username)).filter(
            passwd=password).first()
        if user_object:
            # 登录成功为止1
            request.session['user_id'] = user_object.id
            request.session.set_expiry(60 * 60 * 24 * 14)

            # return redirect('/index/')
            return redirect(reverse('index'))

        form.add_error('username', '用户名或密码错误')

    return render(request, 'login.html', {'form': form})



def image_code(request):
    image_object, code = create_validate_code()


    request.session['image_code'] = code
    request.session.set_expiry(60)  # 主动修改session的过期时间为60s

    stream = BytesIO()
    image_object.save(stream, 'png')
    return HttpResponse(stream.getvalue())


def index(request):
    return render(request,'index.html',locals())


def project_list(request):

    return HttpResponse('施工中。。。。')
    # form = ProjectModelForm()
    # return render(request,'project_list.html',{'form':form})

def logout(request):
    request.session.flush()
    return redirect(reverse('index'))